#!/usr/bin/env python

import optparse
import os
import os.path
import sys

import charmicat

def main():
    '''
    ccat_report.py [opts] module cutset path

    Write a text file with details of the efficiencies and event counts of the cuts 
    of `cutset' in `path'. 
    '''

    op = optparse.OptionParser(usage=main.__doc__)

    op.add_option("-c", "--cutset", dest="cutsets", action='append', default=[],
                  help="Write report for cutset NAME (can be used more than once)")
    op.add_option("-o", "--output", dest="output", default="cut_summary.txt", 
                  help="Save summary in FILE", metavar="FILE")
    op.add_option("-r", "--replace", action="append", dest="replace", default=[], nargs=2,
                  help="Replace in cutset cut named CUT1 with cut named CUT2")
    op.add_option("-s", dest="list", action='append', default=[],
                  help="Write a report for cut NAME (can be used more than once)")
    op.add_option("-t", "--title", dest='title', default=None,
                  help="Write TITLE as the title for the summary", metavar="TITLE")

    opts, args = op.parse_args()

    if len(args) < 1:
        msg = "Please supply the name of an analysis package, "
        msg += "a cutset within that package, "
        msg += "and a path to a directory where those cuts have been applied.\n"
        raise charmicat.BadCommandLineError(msg, -1)

    module_name = args.pop(0)
 
    charmicat.safe_import(module_name)
        
    if len(args) == 0:
        sys.stderr.write("Please supply a cutset and a path to a directory where those cuts have been applied.\n")
        raise charmicat.BadCommandLineError(msg, -2)

    if not opts.title:
        opts.title = module.channel_latex + " cut summary:"

    cut_list = charmicat.build_cut_list(module, opts)
                
    max_name_len = max([len(cut.name) for cut in cut_list])
    max_desc_len = max([len(cut.desc) for cut in cut_list])

    if max_desc_len > 70:
        max_desc_len = 70

    with open(opts.output, 'w') as fpout:
        fpout.write(opts.title + "\n\n")

        hdrstr = "{0:{max_name_len}} {1:{max_desc_len}} {2:>10} {3:>14} {4:>10}\n"
        rowstr = "{0:{max_name_len}} {1:{max_desc_len}} {2:>10} {3:>14} {4:>10.4f}\n"

        fpout.write(hdrstr.format('Cut name', 'Cut description', 'Events in', 'Events passed', '% kept',
                                  max_name_len=max_name_len, max_desc_len=max_desc_len, ))
        fpout.write('\n')

        initial_eventcount = -1
        for cut in cut_list:    
            print cut.name
            cut_dir = os.path.join(os.getcwd(), cut.name)
            os.chdir(cut_dir)

            report_fname = os.path.join(cut_dir, 'report.txt')

            if os.access('report.txt', os.F_OK):
                npass, ntot = charmicat.report.parse(report_fname)
            else:
                npass, ntot = charmicat.report.generate(cut_dir) 

            percent = float(npass) / float(ntot)

            try: 
                fpout.write(rowstr.format(cut.name, 
                                          cut.desc[:max_desc_len], 
                                          ntot, 
                                          npass, 
                                          percent,
                                          max_name_len=max_name_len, 
                                          max_desc_len=max_desc_len, 
                                          )
                            )
            except AttributeError:
                fpout.write(rowstr.format(cut.name, 
                                          '<none specified>', 
                                          ntot, 
                                          npass, 
                                          percent,
                                          max_name_len=max_name_len, 
                                          max_desc_len=max_desc_len,
                                          )
                            )



if __name__ == "__main__":
    try:
        sys.exit(main())
    except charmicat.BadCommandLineError, e:
        import os
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("See `{0} -h' for more.\n".format(os.path.basename(sys.argv[0])))
        sys.stderr.flush()
        sys.exit(e.retcode)

